import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { FieldEntity } from './field.entity';
import { Between } from 'typeorm';
import * as dayjs from 'dayjs';

@Injectable()
export class FieldService {
  constructor(
    @InjectRepository(FieldEntity)
    private readonly fieldRepository: Repository<FieldEntity>,
  ) {}
  async saveField(param) {
    const { users = [], min, max, precision,regEx, ...restParam } = param;

    // restParam.users = users.map(id => {
    //   return { id };
    // });
    if (!restParam.id) {
      restParam.createDate = dayjs().format('YYYY-MM-DD HH:mm:ss');
    }
    this.fieldRepository.save({
      min: min || null,
      max: max || null,
      precision: precision || null,
      regEx: regEx || null,
      ...restParam,
    });
  }

  async saveFieldList(param) {
    const { fieldList } = param;
    this.fieldRepository.save(fieldList);
  }
  async getFieldList(param) {
    const {
      current,
      pageSize,
      noPagination,
      orderParam,
      createDateRange,
      ...restParam
    } = param;
    let where = {
      ...restParam,
      createDate: Between(createDateRange?.[0], createDateRange?.[1]),
    };
    if (!createDateRange) {
      delete where.createDate;
    }

    let data = await this.fieldRepository.findAndCount({
      where,
      skip: noPagination ? undefined : (current - 1) * pageSize,
      take: noPagination ? undefined : pageSize,
      order: Object.keys(orderParam || {}).length
        ? orderParam
        : { order: 'ASC' },
    });

    return { data: data[0], total: data[1], current, pageSize };
  }

  async getField(param) {
    return await this.fieldRepository.findOne({
      where: param,
      // relations: ['users'],
    });
  }

  async delFieldList(param) {
    const { idList } = param;
    let data = await this.fieldRepository.findByIds(idList);
    return await this.fieldRepository.remove(data);
  }
}
